package com.yilin.tms.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yilin.commons.exception.BusinessException;
import com.yilin.commons.util.ArrayUtil;
import com.yilin.tms.core.entity.user.technical.TechnicalFeeRule;
import com.yilin.tms.core.entity.user.technical.TechnicalFeeRuleItem;
import com.yilin.tms.user.service.ITechnicalFeeService;
import com.yilin.tms.user.mapper.UserTechnicalFeeRuleItemMapper;
import com.yilin.tms.user.mapper.UserTechnicalFeeRuleMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class TechnicalFeeService extends ServiceImpl<UserTechnicalFeeRuleMapper, TechnicalFeeRule> implements ITechnicalFeeService {

    @Resource
    UserTechnicalFeeRuleMapper technicalFeeRuleMapper;
    @Resource
    UserTechnicalFeeRuleItemMapper technicalFeeRuleItemMapper;

    @Override
    public TechnicalFeeRule getTechnicalFeeRule() {
        QueryWrapper<TechnicalFeeRule> queryWrapper = new QueryWrapper<>();
        List<TechnicalFeeRule> technicalFeeRules = technicalFeeRuleMapper.selectList(queryWrapper);
        TechnicalFeeRule technicalFeeRule = ArrayUtil.first(technicalFeeRules);
        if (technicalFeeRule==null) return null;
        QueryWrapper<TechnicalFeeRuleItem> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("fee_rule_id", technicalFeeRule.getId());
        queryWrapper2.orderByAsc("start_fee");
        List<TechnicalFeeRuleItem> itemList = technicalFeeRuleItemMapper.selectList(queryWrapper2);
        technicalFeeRule.setRuleItems(itemList);
        return technicalFeeRule;
    }

    @Override
    public void saveOrUpdateRule(TechnicalFeeRule rule) {
        if (rule.getRuleItems().size() < 2) throw new BusinessException("计费阶梯不得低于2项");
        for (TechnicalFeeRuleItem item : rule.getRuleItems()) {
            if (item.getIsRate() == null) throw new BusinessException("计费规则方式为空");
            if (item.getEndNoLimited() == null) throw new BusinessException("数据不合规【endNoLimited】");
            if (item.getDisabled() == null) throw new BusinessException("数据不合规【disabled】");
        }
        //变更规则
        if (rule.getId() == null) technicalFeeRuleMapper.insert(rule);
        else technicalFeeRuleMapper.updateById(rule);
        //全部删除规则项
        QueryWrapper<TechnicalFeeRuleItem> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("fee_rule_id", rule.getId());
        technicalFeeRuleItemMapper.delete(queryWrapper);
        //重新生產規則
        for (TechnicalFeeRuleItem item : rule.getRuleItems()) {
            item.setFeeRuleId(rule.getId());
            technicalFeeRuleItemMapper.insert(item);
        }
    }


}
